package scheduler

import (
	"spider/engine"
)

type QueuedScheduler struct {
	requestChan chan engine.Request
	workerChan  chan chan engine.Request
}

func (s *QueuedScheduler) Submit(r engine.Request) {
	s.requestChan <- r
}

func (s *QueuedScheduler) WorkerReady(r chan engine.Request) {
	s.workerChan <- r
}

func (s *QueuedScheduler) WorkerChan() chan engine.Request {
	return make(chan engine.Request)
}
func (s *QueuedScheduler) Run() {
	s.workerChan = make(chan chan engine.Request)
	s.requestChan = make(chan engine.Request)
	go func() {
		var requestQue []engine.Request
		var workerQue []chan engine.Request
		for {
			var activeRequest engine.Request
			var activeWorker chan engine.Request
			if len(requestQue) > 0 && len(workerQue) > 0 {
				activeRequest = requestQue[0]
				activeWorker = workerQue[0]
			}
			select {
			case r := <-s.requestChan:
				requestQue = append(requestQue, r)
			case w := <-s.workerChan:
				workerQue = append(workerQue, w)
				//对应routine收到信息 (concurrent.go func createWorker) request <- in
			case activeWorker <- activeRequest:
				workerQue = workerQue[1:]
				requestQue = requestQue[1:]
			}
		}
	}()
}
